package top.pmwly.thymeleaf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import top.pmwly.thymeleaf.hadler.MyAccessDeniedHandler;
import top.pmwly.thymeleaf.hadler.MyAuthentiactionFailurHandler;
import top.pmwly.thymeleaf.service.LoginServiceImpl;


import javax.sql.DataSource;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName SpringSecurity.java
 * @Description springSecurity 配置类
 * @createTime 2021年08月19日 17:03:00
 */
@Configuration
public class SpringSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;





    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .successForwardUrl("/toMain")
                .usernameParameter("username")
                .passwordParameter("password")
                .failureForwardUrl("/toError");

        //授权
        http.authorizeRequests()
                .antMatchers("/login.html").permitAll()
                .antMatchers("/error.html").permitAll()
                .anyRequest().authenticated();

        //关闭crs防火墙
        http.csrf().disable();

        //异常权限处理
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

        //退出登录
        http.logout()
                //自定义的退出登录的url
                //.logoutUrl("/user/logout")
                //退出登录跳转登录页面
                //清空session
                //.invalidateHttpSession(true)
                //清空认证
                //.clearAuthentication(true)
                .logoutSuccessUrl("/login.html");
    }



    /**
     * 密码解析器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
